package com.pinkmeet.dao;

import com.pinkmeet.util.DBUtil;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * Created by mars on 2018/5/9.
 */
public class ConnDAO {
    private Connection conn;


    public ConnDAO(){
        conn = DBUtil.getConnection();
    }

    public boolean isChatById(int id){
        String sql ="SELECT * FROM conn WHERE cid = ? OR ccid = ?";
        PreparedStatement pstmt = null;

        try{
            pstmt = this.conn.prepareStatement(sql);
            pstmt.setInt(1,id);
            pstmt.setInt(2,id);
            ResultSet res = pstmt.executeQuery();
            if (res.next()){
                return  true;
            }

        }catch (SQLException e){
            e.printStackTrace();

        }
        return false;
    }

    //通过用户id获取聊天对象
    public int getChatById(int id){
        String sql = "SELECT * FROM conn WHERE cid = ? OR ccid = ?";
        PreparedStatement pstmt = null;
        int cid,ccid;
        try{
            pstmt = this.conn.prepareStatement(sql);
            pstmt.setInt(1,id);
            pstmt.setInt(2,id);
            ResultSet res = pstmt.executeQuery();
            cid = res.getInt("cid");
            ccid = res.getInt("ccid");
            if (cid != id ){
                return cid;
            }else {
                return ccid;
            }

        }catch (SQLException e){
            e.printStackTrace();
        }
        return  -1;
    }

    public boolean setChat(int cid, int ccid){
        String sql = "INSERT INTO conn (cid,ccid,c_time) VALUES (?,?,?)";
        PreparedStatement pstmt = null;
        try {
            pstmt = this.conn.prepareStatement(sql);
            pstmt.setInt(1,cid);
            pstmt.setInt(2,ccid);

            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            pstmt.setDate(3, java.sql.Date.valueOf(sdf.format(d)));

            return  true;

        }catch (SQLException e){
            e.printStackTrace();
            return  false;
        }

    }

    public boolean deltChatById(int uid){
        String sql = "DELETE FROM conn WHERE cid = ? OR ccid = ?";
        PreparedStatement pstmt = null;
        try {
            pstmt = this.conn.prepareStatement(sql);
            pstmt.setInt(1,uid);
            pstmt.setInt(2,uid);
            pstmt.execute();
            return true;
        }catch (SQLException e){
            e.printStackTrace();
        }
        return false;
    }







}
